import pandas as pd
import numpy as np
from common.config import torqueConfig as Config

import os

class RegressDecorator:


    def regress(func):

        def argmin(x):
            return np.argmin(x)

        def wrapper(scatterFileName, surfaceFileName):
            print('RegressDecorator.regress 进行中................')
            while(True):
                X_scatter = pd.read_csv(scatterFileName)
                #print("X_scatter: ", X_scatter)
                X_surface = pd.read_csv(surfaceFileName)
                #print("len(X_surface): ", len(X_surface))

                len_X_scatter = len(X_scatter)  # 拟合前的点数
                len_X_surface = len(X_surface)  # 拟合后的点数

                windSpeeds = X_surface[Config.WindSpeed].drop_duplicates().values  # 拟合后的speed轴节点
                len_windSpeeds = len(windSpeeds)
                windSpeeds_ex = np.array([windSpeeds for _ in range(len_X_scatter)])  # 扩展成 np.array[ 散点数, speed轴格点数 ]

                RotateSpeeds = X_surface[Config.RotateSpeed].drop_duplicates().values  # 拟合后的direction轴节点
                len_RotateSpeeds = len(RotateSpeeds)
                RotateSpeeds_ex = np.array([RotateSpeeds for _ in range(len_X_scatter)])  # 扩展成 np.array[ 散点数, direction轴格点数 ]

                actPowers_afterFit = X_surface[Config.ActPower].values.reshape([len_windSpeeds, len_RotateSpeeds])  # 各格点拟合值，【注意】：要求拟合后数据文件数据有序，且排列关键字 speed（主），direction（次）

                speedComp = abs(windSpeeds_ex - np.array([X_scatter[Config.WindSpeed].values for _ in range(len_windSpeeds)]).T)  #
                indexs_speed = list(map(argmin, speedComp))  # 各个散点离 speed 轴那个格点最近

                directionComp = abs(RotateSpeeds_ex - np.array([X_scatter[Config.RotateSpeed].values for _ in range(len_RotateSpeeds)]).T)
                indexs_direction = list(map(argmin, directionComp))  # 各个散点离 direction 轴哪个格点最近

                #print("indexs_x: ", indexs_speed)
                #print("indexs_y: ", indexs_direction)


                is_reserve = np.array(abs(X_scatter[Config.ActPower]-actPowers_afterFit[indexs_speed, indexs_direction]) < 100 + Config.filterFactor*actPowers_afterFit[indexs_speed, indexs_direction])  # 标记散点是否保留
                if False not in list(is_reserve):  # 如果都是True
                    print("数据点剔除完毕...............")
                    break

                print(f"剔除了{len_X_scatter-is_reserve.sum()}个数据点")
                X_scatter = X_scatter[is_reserve]  # 剔除数据点
                X_scatter.to_csv(scatterFileName, index=False)
                os.system("python surfaceProcess.py")  # 重新拟合并剔除数据点

            return func(" ", " ")
        return wrapper

